package com.kensure.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import co.kensure.api.ApiDesc;
import co.kensure.api.ApiUtil;
import co.kensure.exception.BusinessExceptionUtil;

import com.kensure.shike.constant.BusiConstant;
import com.kensure.shike.user.model.SKUser;
import com.kensure.shike.user.service.SKLoginService;
import com.kensure.shike.user.service.SKUserService;

public class ControllerInterceptor extends HandlerInterceptorAdapter {

	@Resource
	private SKUserService sKUserService;
	
	@Resource
	private SKLoginService sKLoginService;

	private static Map<Integer,String> authmap = new HashMap<>();
	private static Map<String,String> loginmap = new HashMap<>();
	static{
		authmap.put(1, "user");
		authmap.put(2, "saler");
		authmap.put(3, "admin");
		
		loginmap.put("skm", "/skm/login");
		loginmap.put("shangjia", "/shangjia/login");
		loginmap.put("gl", "/gl/login");
	}
	
	// 请求之前
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 返回一个action
		String serverPath = request.getServletPath();
		ApiDesc api = ApiUtil.get(serverPath);
		String title = BusiConstant.name;
		
		SKUser user = null;
		if(!serverPath.endsWith(".do")){
			user = sKUserService.getUser();
			request.setAttribute("curentuser", user);
		}
		
		if (api != null) {
		
			
			title = api.getName();
			if(user == null){
				user = sKUserService.getUser();
			}
			
			
			//put的数据，进行重复性认证
			if("put".equals(api.getType())){
				if(user != null){
					long userid = user.getId();
					KeyLock.doLock(userid+"");
				}
			}			
		}
		request.setAttribute("wangzhangtitle", title);
		return true;
	}
	
	
	
	
	
	@Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
     
    }
 
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    	KeyLock.unlock();
    }


	
	private String jiexi(String url){
		String loginUrl = loginmap.get("skm");
		if(url.contains("/skm/")){
			
		}else if(url.contains("/shangjia/")){
			
		}else if(url.contains("/gl/")){
			
		}	
		return ApiUtil.getUrl(loginUrl);
	}

}